package com.zzjson.cloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.cloud</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年09月09日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
@EnableEurekaClient
@EnableAutoConfiguration
@RestController()
@RequestMapping("/services")
public class EurekaClientApplication {

	@Autowired
	private DiscoveryClient discoveryClient;

	public static void main(String[] args) {
		new SpringApplicationBuilder(EurekaClientApplication.class)
				.web(WebApplicationType.SERVLET).
				run();
	}

	@GetMapping("/")
	public Set<String> getServices() {
		return new LinkedHashSet<>(discoveryClient.getServices());
	}

	/**
	 * @param serviceName
	 * @return
	 * @PathParam 属于 JAX-RS 标准 Java REST 注解
	 * @PathVariable 属于 Spring Web MVC
	 */
	@GetMapping("/{serviceName}")
	public List<ServiceInstance> getServiceInstances(@PathVariable String serviceName) {
		return discoveryClient.getInstances(serviceName);
	}

	@GetMapping("/{serviceName}/{instanceId}")
	public ServiceInstance getServiceInstance(@PathVariable String serviceName, @PathVariable String instanceId) {
		return getServiceInstances(serviceName)
				.stream()
				.filter(serviceInstance -> instanceId.equals(serviceInstance.getInstanceId()))
				.findFirst()
				.orElseThrow(() -> new RuntimeException("No Such service instance"));
	}

}